﻿using BLL;
using COMMON;
using IBLL;
using MODEL;
using Shop.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Shop.Controllers
{
    public class ProductCategoryController : Controller
    {
        //侯海啸
        IProductCategoryBLL bll = new ProductCategoryBLL();

        // GET: ProductCategory
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public ActionResult Add()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Add(ProductCategory category)
        {
            if (!ModelState.IsValid) {
                foreach (ModelState modelState in ModelState.Values) {
                    foreach (ModelError error in modelState.Errors) {
                        return Json(new { state = false, msg = error.ErrorMessage });

                    }
                }

            }
            //侯海啸

            var file = Request.Files["file"];
            //1判断上传文件类型（.jpg,.jpeg,.png,.gif），类型检测不通过，直接返回
            if (file == null)
            {
                return Json(new { state = false, msg = "图片不存在" });
            }
            byte[] bytes = Common.StreamToBytes(file.InputStream);
            FileExtension fileExtension = FileHelper.CheckTextFile(bytes);
            if (fileExtension == FileExtension.VALIDFILE) {
                return Json(new { state = false, msg = "上传文件已损坏" });
            }
            if (!(fileExtension == FileExtension.GIF || fileExtension == FileExtension.JPG || fileExtension == FileExtension.PNG)) {
                return Json(new { state = false, msg = "上传的文件类型有误" });
            }
            //2生成新的文件名：201705141122334444（yyyyMMddHHmmssfffff）+五位随机数
            DateTime dt = DateTime.Now;

            Random random = new Random();
            int randomNum = random.Next(10000, 99999);
            string extension = Path.GetExtension(file.FileName);
            string newFileName = dt.ToString("yyyyMMddHHmmssfffff") + randomNum.ToString() + extension;
            //3将图片保存到服务器

            //根据相对路径获取绝对路径Server.MapPath("/CategoryImages/")
            file.SaveAs(Server.MapPath("/CategoryImages/") + newFileName);
            //4将数据保存到数据库
            category.CreateTime = DateTime.Now;
            category.Img = newFileName;
            bll.Add(category);
            return Json(new { state = true, msg = "添加成功" });
        }

        public ActionResult List() {

            return View();
        }
        [HttpPost]
        public ActionResult GetAll(int draw)
        {
            //侯海啸
            var rootLIst = bll.GetSub(0);
            List<ProductCategoryVModel> list = new List<ProductCategoryVModel>();
            foreach (var category in rootLIst)
            {
                ProductCategoryVModel vModel = new ProductCategoryVModel();
                vModel.ID = category.ID;
                vModel.Name = category.Name;
                vModel.OrderNum = category.OrderNum;
                vModel.Img = category.Img;
                vModel.PID = category.PID;
                vModel.children = new List<ProductCategoryVModel>();
                GetSub(vModel);
                list.Add(vModel);
            }

            var result = new { draw = draw, data = list };
            return Json(result);
        }
        private void GetSub(ProductCategoryVModel parentNode) {
            var subList = bll.GetSub(parentNode.ID);
            if (subList.Count == 0) {
                return;
            }
            foreach (var category in subList)
            {
                ProductCategoryVModel vModel = new ProductCategoryVModel();
                vModel.ID = category.ID;
                vModel.Name = category.Name;
                vModel.OrderNum = category.OrderNum;
                vModel.Img = category.Img;
                vModel.PID = category.PID;
                vModel.children = new List<ProductCategoryVModel>();
                GetSub(vModel);
                parentNode.children.Add(vModel);
            }
        }
        public ActionResult Del(int id) {

            int result = bll.Delete(id);

            return Json(new { state = result > 0 ? true : false, msg = "删除成功" });
        }

        [HttpGet]
        public ActionResult Update(int id) {
            ProductCategory category = bll.GetOne(id);
            List<ProductCategory> categories = bll.GetAll();
            ProductCategoryUpdateVModel vModel = new ProductCategoryUpdateVModel() {
                Category = category,
                Categories = categories
            };
            return View(vModel);

        }
        [HttpPost]
        public ActionResult Update(ProductCategory category)
        {
            var file = Request.Files["file"];
            //1判断上传文件类型（.jpg,.jpeg,.png,.gif），类型检测不通过，直接返回
            if (file == null)
            {
            }
            else {
                byte[] bytes = Common.StreamToBytes(file.InputStream);
                FileExtension fileExtension = FileHelper.CheckTextFile(bytes);
                if (fileExtension == FileExtension.VALIDFILE)
                {
                    return Json(new { state = false, msg = "上传文件已损坏" });
                }
                if (!(fileExtension == FileExtension.GIF || fileExtension == FileExtension.JPG || fileExtension == FileExtension.PNG))
                {
                    return Json(new { state = false, msg = "上传的文件类型有误" });
                }
                //2生成新的文件名：201705141122334444（yyyyMMddHHmmssfffff）+五位随机数
                DateTime dt = DateTime.Now;

                Random random = new Random();
                int randomNum = random.Next(10000, 99999);
                string extension = Path.GetExtension(file.FileName);
                string newFileName = dt.ToString("yyyyMMddHHmmssfffff") + randomNum.ToString() + extension;
                //3将图片保存到服务器

                //根据相对路径获取绝对路径Server.MapPath("/CategoryImages/")
                file.SaveAs(Server.MapPath("/CategoryImages/") + newFileName);
                //4将数据保存到数据库

                category.Img = newFileName;
            }
            int result = bll.Update(category);
            return Json(new { state = result > 0 ? true : false });

        }
        [HttpGet]
        public ActionResult GetByPID(int pid) {
            var list = bll.GetSub(pid);
            return Json(list, JsonRequestBehavior.AllowGet);
        }
    }
   
}